package cn.gs.serializable.serialize;

// @author gs
import cn.gs.reflect.ProxyTool;
import java.lang.reflect.Constructor;

public abstract class AGenericSerialize implements ISerialize {

    protected ISerialize ss = null;
    protected Class<?> cc = null;

    protected ISerialize serialize(ISerialize ctrl) {
        return ss == null ? ctrl : ss;
    }

    public AGenericSerialize() {
    }

    public AGenericSerialize(ISerialize ss) {
        this.ss = ss;
    }

    public AGenericSerialize(Class<?> cc) {
        this.cc = cc;
    }

    protected <T> T create(Class<T> clazz, Object proxy) {
        if (clazz == null) {
            return (T) proxy;
        }
        try {
            T ins = clazz.newInstance();
            return ins;
        } catch (Throwable ex) {
        }
        for (Constructor c : clazz.getConstructors()) {
            try {
                if (c.getParameterTypes().length == 1 && clazz.isAssignableFrom(c.getParameterTypes()[0])) {
                    T ins = (T) c.newInstance(proxy);
                    return ins;
                }
            } catch (Throwable ex) {
            }
        }
        try {
            return ProxyTool.create(proxy, clazz);
        } catch (Throwable ex) {
        }
        return null;
    }
}
